<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
    <link rel="stylesheet" href="${pageContext.request.contextPath}/layui/css/layui.css">
    <script src="${pageContext.request.contextPath}/layui/layui.js" charset="utf-8"></script>
</head>
<body>
<%--添加和修改的弹出框--%>
<div id="addRoleDiv" style="display: none">
    <form class="layui-form" id="editForm" lay-filter="editForm">
        <input name="rid" style="display: none">
        <br>
        <div class="layui-form-item">
            <label class="layui-form-label">角色名</label>
            <div class="layui-input-inline">
                <input type="text" name="rname" class="layui-input" lay-verify="required">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">角色描述</label>
            <div class="layui-input-inline">
                <input type="text" name="memo" class="layui-input" lay-verify="required">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">角色状态</label>
            <div class="layui-input-inline">
                <select  name="status" lay-verify="required">
                    <option value="请选择"></option>
                    <option value="0">禁用</option>
                    <option value="1">启用</option>
                </select>
            </div>
        </div>
        <div class="layui-form-item">
            <div class="layui-input-block">
                <button type="button" id="btnSub" class="layui-btn" lay-submit lay-filter="editRole">确认</button>
            </div>
        </div>
    </form>
</div>
<table class="layui-hide" id="test" lay-filter="test"></table>
<div id="treeDemo" style="display: none">
    <div id="test1"></div>
    <%--提交修改权限的按钮--%>
    <button class="layui-btn layui-btn-sm" id="subPer">提交权限修改</button>
</div>
<script type="text/html" id="toolbarDemo">
    <div class="layui-btn-container">
        <%--<button class="layui-btn layui-btn-sm" lay-event="getCheckData">获取选中行数据</button>
        <button class="layui-btn layui-btn-sm" lay-event="getCheckLength">获取选中数目</button>--%>
        <button class="layui-btn layui-btn-sm" lay-event="addRole">新增角色</button>
    </div>
</script>
<script type="text/html" id="barDemo">
    <a class="layui-btn layui-btn-xs" lay-event="edit">编辑</a>
    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="update">修改权限</a>
</script>
<script>
    layui.use(['table','jquery','layer','form','tree'], function(){
        var table = layui.table;
        var $  = layui.jquery;
        var layer = layui.layer;
        var form = layui.form;
        var tree = layui.tree;

        //当页面加载时执行的方法
        $(function (){
            showtable();
        })
        //页面加载时，先查询所有的菜单信息并展示
        function loadPremission(){
            $.ajax({
                url:'${pageContext.request.contextPath}/menu/getAllMenu',
                type:"get",
                async:false,
                success:function (treeData){
                    //请求成功后加载树形菜单
                    tree.render({
                        elem: '#test1'
                        ,data:treeData
                        ,showCheckbox:true
                        ,id: 'demoId' //定义索引
                        ,click: function(obj){
                            console.log(obj.data); //得到当前点击的节点数据
                            /*console.log(obj.state); //得到当前节点的展开状态：open、close、normal
                            console.log(obj.elem); //得到当前节点元素*/

                            console.log(obj.data.children); //当前节点下是否有子节点
                        }
                    });
                }
            })
        }

        //展示角色信息的方法
        function showtable(){
            table.render({
                elem: '#test'
                ,url:'${pageContext.request.contextPath}/role/getAllRole'
                ,toolbar: '#toolbarDemo' //开启头部工具栏，并为其绑定左侧模板
                ,defaultToolbar: ['filter', 'exports', 'print', { //自定义头部工具栏右侧图标。如无需自定义，去除该参数即可
                    title: '提示'
                    ,layEvent: 'LAYTABLE_TIPS'
                    ,icon: 'layui-icon-tips'
                }]
                ,title: '用户数据表'
                ,cols: [[
                    {type: 'checkbox', fixed: 'left'}
                    ,{field:'rid', title:'ID', fixed: 'left', unresize: true, sort: true}
                    ,{field:'rname', title:'角色名'}
                    ,{field:'memo', title:'角色描述'}
                    ,{field:'status', title:'状态',  sort: true,templet: function(d){
                            if (d.status==0){
                                return '<button type="button" class="layui-btn layui-btn-xs">禁用</button>';
                            }else{
                                return '<button type="button" class="layui-btn layui-btn-xs">启用</button>';
                            }
                        }}
                    ,{fixed: 'right', title:'操作', toolbar: '#barDemo'}
                ]]
                ,page: true
            });
        }


        //新增和修改角色的表单提交事件
        form.on('submit(editRole)', function (data){
            $.ajax({
                type: "post",
                url: "${pageContext.request.contextPath}/role/editRole",
                //dataType: 'json',
                data:data.field,
                success: function (result) {
                    //alert(result!=null);
                    if (result.code == 200 ){
                        layer.closeAll();
                        showtable();
                        layer.msg(result.msg);
                    }else{
                        layer.msg(result.msg);
                    }
                }
            });
        });



        //头工具栏事件
        table.on('toolbar(test)', function(obj){
            var checkStatus = table.checkStatus(obj.config.id);
            switch(obj.event){
                case 'getCheckData':
                    var data = checkStatus.data;
                    layer.alert(JSON.stringify(data));
                    break;
                case 'getCheckLength':
                    var data = checkStatus.data;
                    layer.msg('选中了：'+ data.length + ' 个');
                    break;
                case 'addRole':
                    //打开弹出框时先清空
                    $("#editForm")[0].reset();
                    layer.open({
                        type: 1,
                        anim: 3,
                        title: ['添加角色', 'font-size:20px'],
                        content: $("#addRoleDiv"),
                        offset: '50px',
                        area: '400px'
                    })
                    break;

                //自定义头工具栏右侧图标 - 提示
                case 'LAYTABLE_TIPS':
                    layer.alert('这是工具栏右侧自定义的一个图标按钮');
                    break;
            };
        });

        //监听行工具事件
        var rowData;
        table.on('tool(test)', function(obj){
            var data = obj.data;
            rowData = obj.data;
            //console.log(obj)
            if(obj.event === 'del'){
                layer.confirm('真的删除行么', function(index){
                    obj.del();
                    layer.close(index);
                });
            } else if(obj.event === 'edit'){
                //打开弹出框时先清空
                $("#editForm")[0].reset();
                layer.open({
                    type: 1,
                    anim: 3,
                    title: ['修改角色', 'font-size:20px'],
                    content: $("#addRoleDiv"),
                    offset: '50px',
                    area: '400px',
                    success:function (){
                        form.val("editForm",data);//点击编辑时，填充数据
                    }
                })
            }else if (obj.event==='update'){//修改权限的弹出框
                //重新执行加载所有权限的方法
                loadPremission();
                layer.open({
                    type: 1,
                    anim: 3,
                    title: ['修改权限', 'font-size:20px'],
                    content: $("#treeDemo"),
                    offset: '0px',
                    area:['300px']
                })
                $.ajax({
                    type:"post",
                    url:'${pageContext.request.contextPath}/menu/getAllMidByRid',
                    data:{"rid":data.rid},
                    success:function (midData){
                        //alert(JSON.stringify(midData))
                        tree.setChecked('demoId', midData); //批量勾选 id 为 2、3 的节点
                    }
                })
            }
        });
        //提交修改的权限
        $("#subPer").click(function (){
            var checkData = tree.getChecked('demoId');
            //定义一个数组用来存储取出的所有id(包括父id和子id)
            var midArr = [];
            for (var i=0;i<checkData.length;i++){
                //将父id加到数组中
                midArr.push(checkData[i].id);
                for(var j=0;j<checkData[i].children.length;j++){
                    //将子id加到数组中
                    midArr.push(checkData[i].children[j].id)
                    //alert(checkData[i].children[j].id)
                }
            }
            //alert(midArr);
            $.ajax({
                type:'post',
                url:'${pageContext.request.contextPath}/menu/editPremission',
                data:{"rid":rowData.rid,"midArr":midArr+""},
                dataType:'json',
                success:function (resultData){
                    layer.closeAll();
                    if (resultData.code == 1 ){
                        layer.msg(resultData.msg, {icon: 1});
                    }else{
                        layer.msg(resultData.msg, {icon: 5});
                    }
                }
            })
        })
    });
</script>
</body>
</html>
